const Koa = require('koa')
const router = require('koa-router')()
const bodyParser = require('koa-bodyparser')
const database = require('./src/database/core')

// 使用Koa2作为服务端
const app = new Koa()
// 设置跨域中间件
app.use(async (ctx, next)=> {
    ctx.set('Access-Control-Allow-Origin', 'http://localhost:9000')  // 跨域的范围是无人机项目的域名
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
    // 保证OPTIONS能返回200
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200;
    } else {
        await next();
    }
});
// 使用正文解析中间件
app.use(bodyParser())
// 设置路由
router.get('/', async (ctx, next) => {
    const name = ctx.params.name
    ctx.response.body = `<h1>请访问http://localhost:3001/save保存数据!</h1>`
})
router.post('/save', async (ctx, next) => {
    const data = ctx.request.body.data
    const dataJson = JSON.parse(data)
    database.record.insert(dataJson, (err, newDoc) => {
        if (err) {
            console.log(err)
        } else {
            console.log(newDoc)
        }
    })
    ctx.response.type = "application/json"
    ctx.response.body = JSON.stringify({
        status: "success"
    })
})

router.post('/saveDeploy', async (ctx, next) => {
    const data = ctx.request.body.data
    const dataJson = JSON.parse(data)
    database.deploy.insert(dataJson, (err, newDoc) => {
        if (err) {
            console.log(err)
        } else {
            console.log(newDoc)
        }
    })
    ctx.response.type = "application/json"
    ctx.response.body = JSON.stringify({
        status: "success"
    })
})
// 使用路由
app.use(router.routes())
// 监听3000端口
app.listen(3001)
console.log("server is start in port:3001")